package com.wlyy.his.ze.hepler;





import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;


/**
 * @author 10097
 */
@SuppressWarnings("unchecked")
public class XMLUtil {

	/**
	 * 将对象转成XML
	 */
	public static String bean2xml(Object object) {
		StringWriter writer = new StringWriter();
		JAXBContext context;
		try {
			context = JAXBContext.newInstance(object.getClass());
			Marshaller marshaller = context.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
			marshaller.marshal(object, writer);
		} catch (JAXBException e) {

			//log.info("对象转XML错误,obj={},err={}", object, e);
		}

		return writer.getBuffer().toString();
	}

	/**
	 * 将XML转成java对象
	 * 
	 * @param xml
	 * @param clazz
	 * @return
	 * @throws JAXBException 
	 */
	@SuppressWarnings("unchecked")
	public static <T> T xml2bean(String xml, Class<?> clazz) throws JAXBException {
		JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
		Unmarshaller um = jaxbContext.createUnmarshaller();
		StreamSource streamSource = new StreamSource(new StringReader(xml));		
		return (T) um.unmarshal(streamSource);
	}
	
	/**
	 * 将XML转成java对象
	 * 
	 * @param clazz
	 * @return
	 * @throws JAXBException 
	 */
	@SuppressWarnings("unchecked")
	public static <T> T xml2bean(File file , Class<?> clazz) throws JAXBException {
		JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
		Unmarshaller um = jaxbContext.createUnmarshaller();
		return (T) um.unmarshal(file);
	}

	public static <T>  T xml2bean(Class<T> c, String xml) throws JAXBException{		
		return (T)XMLUtil.xml2bean(xml, c);		
	}
}
